package org.jeecg.modules.sxaq.ior.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sxaq.ior.entity.RecordInout;
import org.jeecg.modules.sxaq.ior.service.IRecordInoutService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.sxaq.utils.RedisConstant;
import org.jeecg.modules.sxaq.utils.Urls;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDevice;
import org.jeecg.modules.system.service.ISysUserDeviceService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
  * @Description: 进出场记录
  * @Author: DHC
  * @Date:  2020-12-01
 */
@Api(tags="进出场记录")
@RestController
@RequestMapping("/ior/recordInout")
@Slf4j
public class RecordInoutController extends JeecgController<RecordInout, IRecordInoutService> {
	@Autowired
	private IRecordInoutService recordInoutService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserDeviceService sysUserDeviceService;

	@Value("${sxaq.factoryCode}")
	private String factoryCode;

	 @Value("${sxaq.cloudUrl}")
	 private String cloudUrl;

	 @Autowired
	 private RedisUtil redisUtil;

	/**
	 * 分页列表查询
	 *
	 * @param recordInout
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "进出场记录-分页列表查询")
	@ApiOperation(value="进出场记录-分页列表查询", notes="进出场记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(RecordInout recordInout,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<RecordInout> queryWrapper = QueryGenerator.initQueryWrapper(recordInout, req.getParameterMap());
		 Page<RecordInout> page = new Page<RecordInout>(pageNo, pageSize);
		 IPage<RecordInout> pageList = recordInoutService.page(page, queryWrapper);

		//批量查询用户的所属部门
		//step.1 先拿到全部的 useids
		//step.2 通过 useids，一次性查询用户的所属部门名字
		List<String> userIds = pageList.getRecords().stream().map(RecordInout::getUserId).collect(Collectors.toList());
		if(userIds!=null && userIds.size()>0){
			Map<String,String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
			pageList.getRecords().forEach(item->{
				item.setOrgCodeTxt(useDepNames.get(item.getUserId()));
			});
		}

		 return Result.OK(pageList);
	 }

	 @AutoLog(value = "进出场记录-分页列表查询")
	 @ApiOperation(value="app进出场记录-分页列表查询", notes="进出场记录-分页列表查询")
	 @GetMapping(value = "/recordList")
	 public Result<?> queryAppRecordPageList(RecordInout recordInout,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<RecordInout> queryWrapper = QueryGenerator.initQueryWrapper(recordInout, req.getParameterMap());
		 queryWrapper.orderByDesc("create_time");
		 Page<RecordInout> page = new Page<RecordInout>(pageNo, pageSize);
		 IPage<RecordInout> pageList = recordInoutService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	/**
	 *   添加
	 *
	 * @param recordInout
	 * @return
	 */
	@AutoLog(value = "进出场记录-添加")
	@ApiOperation(value="进出场记录-添加", notes="进出场记录-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody RecordInout recordInout) {
		String workNo = recordInout.getWorkNo();
		SysUser sysUser = sysUserService.getUserByWorkNo(workNo);
		if (sysUser == null) {
			return Result.error("员工不存在");
		}

		// 更新redis进出场状态
		redisUtil.set(RedisConstant.IN_OUT_RECORD + workNo, recordInout.getType() + "/" + System.currentTimeMillis());

		recordInout.setRealname(sysUser.getRealname());
		recordInout.setSysOrgCode(sysUser.getOrgCode());
		recordInout.setUserId(sysUser.getId());
		// eventTime来自web，直接取本地服务器时间
		recordInout.setEventTime(new Date());
		recordInout.setPhone(sysUser.getPhone());
		recordInoutService.save(recordInout);

		// 更新用户进出场事件，用于大屏统计
		sysUser.setEventType(recordInout.getType());
		sysUserService.updateById(sysUser);

		// 取得工号关联的所有设备
		List<SysUserDevice> sysUserDevices = sysUserDeviceService.querySysUserDevice(workNo);
		if (sysUserDevices != null && sysUserDevices.size() > 0) {
			for (SysUserDevice sysUserDevice : sysUserDevices) {
				String mobileSingle = sysUserDevice.getMobileSingle();
				JSONObject inoutObject = (JSONObject) JSONObject.toJSON(recordInout);
				// 发送消息给公有云
				JSONObject jsonObject1 = new JSONObject();
				jsonObject1.put("workNo", workNo);
				jsonObject1.put("mobileSingle", mobileSingle);
				jsonObject1.put("type", "web");
				jsonObject1.put("factoryCode", factoryCode);
				jsonObject1.put("force", true);
				jsonObject1.put("isSuccess", true);
				jsonObject1.put("inoutObject", Result.OK(inoutObject));

				JSONObject json = doPost(cloudUrl + Urls.GUN, jsonObject1);
				if (json != null) {
					boolean success = json.getBoolean("success");
					String message = json.getString("message");
					if (success) {
					} else {
						log.debug("----扫码请求----反馈----失败----" + new Date(System.currentTimeMillis()) + "，员工：" + workNo);
						return Result.error(message);
					}
				} else {
					log.debug("----扫码请求----反馈----失败----" + new Date(System.currentTimeMillis()) + "，员工：" + workNo);
					return Result.error("操作失败！");
				}

				sysUserDevice.setEventType(recordInout.getType());
				sysUserDeviceService.updateById(sysUserDevice);
			}
			// 开闸门
			log.debug("----扫码请求----反馈----成功----" + new Date(System.currentTimeMillis()) + "，员工：" + workNo);
			return Result.OK("操作成功！");
		}

		return Result.OK("操作成功！");
	}

	 public JSONObject doPost(String url, JSONObject data) {
		 HttpClient client = HttpClients.createDefault();

		 // 要调用的接口方法
		 HttpPost post = new HttpPost(url);
		 JSONObject jsonObject = null;
		 try {
			 StringEntity s = new StringEntity(data.toString());
			 s.setContentEncoding("UTF-8");
			 s.setContentType("application/json");
			 post.setEntity(s);
			 post.addHeader("content-type", "application/json");
			 HttpResponse res = client.execute(post);
			 String response1 = EntityUtils.toString(res.getEntity());
			 jsonObject = JSONObject.parseObject(response1);
			 System.out.println(response1);
		 } catch (Exception e) {
			 throw new RuntimeException(e);
		 }
		 return jsonObject;
	 }
	
	/**
	 *  编辑
	 *
	 * @param recordInout
	 * @return
	 */
	@AutoLog(value = "进出场记录-编辑")
//	@ApiOperation(value="进出场记录-编辑", notes="进出场记录-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody RecordInout recordInout) {
		recordInoutService.updateById(recordInout);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进出场记录-通过id删除")
//	@ApiOperation(value="进出场记录-通过id删除", notes="进出场记录-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		recordInoutService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "进出场记录-批量删除")
//	@ApiOperation(value="进出场记录-批量删除", notes="进出场记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.recordInoutService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "进出场记录-通过id查询")
	@ApiOperation(value="进出场记录-通过id查询", notes="进出场记录-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		RecordInout recordInout = recordInoutService.getById(id);
		if(recordInout==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(recordInout);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param recordInout
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RecordInout recordInout) {
        return super.exportXls(request, recordInout, RecordInout.class, "进出场记录");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RecordInout.class);
    }
}
